class Backend::MicopostsController < Backend::BaseController
  before_action :set_micopost, only: [:show, :edit, :update, :destroy,:switch]

  def index
    @search = Micopost.all.ransack(params[:q])
    scope = @search.result
    @micoposts = scope.sorted.page(params[:page])
  end

  def show

  end

  def new
    @micopost = Micopost.new
  end

  def edit
  end

  def create
    @micopost = Micopost.new(micopost_params)

    if @micopost.save
      redirect_to referer_or(backend_micoposts_path), notice: '新增成功'
    else
      flash[:alert] = "新增失败"
      render :new
    end
  end

  def update
    if @micopost.update(micopost_params)
      redirect_to referer_or(backend_micoposts_path), notice: '修改成功'
    else
      flash[:alert] = "修改失败"
      render :edit
    end
  end

  def destroy
    if @micopost.destroy
      redirect_to referer_or(backend_micoposts_path), notice: '删除成功'
    else
      redirect_to referer_or(backend_micoposts_path), alert: "删除失败"
    end
  end


  def switch
    @micopost.active? ? @micopost.forbidden! : @micopost.active!
    redirect_to backend_micoposts_path, notice: @micopost.active? ? "内容审核正常" : "内容违规"
  end

  private
    def set_micopost
      @micopost = Micopost.find(params[:id])
    end

    def micopost_params
      params.require(:micopost).permit!
    end
end
